import os
import re
import shutil


def create_copy_folder(source_folder,copy_number):
    # 获取同级目录下已存在的副本数量
    copy_number = copy_number + 1
    print(copy_number)
    # 构造副本文件夹名字
    copy_folder = f"{source_folder}_{copy_number}"

    # 创建副本文件夹
    shutil.copytree(source_folder, copy_folder)

    return copy_folder

def clear_and_copy_files_by_number(source_folder, source_folder_Scenarios_all, pattern):

    copy_folder_all=[source_folder]
    copy_num = 0
    file_count = 0

    file_list = os.listdir(source_folder_Scenarios_all)
    # 使用列表推导式筛选出以 .json 结尾的文件
    json_files = [file for file in file_list if file.endswith('.json')]

    for i in range(len(json_files)-1):
        # 创建副本文件夹
        copy_folder_all.append(create_copy_folder(source_folder,i))
    # 遍历源文件夹中的文件
    files = os.listdir(source_folder_Scenarios_all)
    total_files = len(files)

    for file_name in files:
        source_file = os.path.join(source_folder_Scenarios_all, file_name)
        print(source_file)

        # 检查文件名是否匹配模式
        match = re.match(pattern, file_name)
        if match:
            # 提取序号
            number = int(match.group(1))
            if file_count % 1 == 0:
                copy_folder = copy_folder_all[copy_num]
                # 清空目标文件夹
                Scenarios_folder = os.path.join(copy_folder, "inputs", "Scenarios")
                if os.path.exists(Scenarios_folder):
                    shutil.rmtree(Scenarios_folder)
                if not os.path.exists(Scenarios_folder):
                    os.makedirs(Scenarios_folder)
                copy_num += 1

            destination_file = os.path.join(Scenarios_folder, file_name)
            print(destination_file)
            # 复制文件到目标文件夹
            shutil.copy(source_file, destination_file)

            file_count += 1

# 测试
current_directory = os.getcwd()
parent_directory = os.path.dirname(current_directory)
source_folder = os.path.join(current_directory)
source_folder_Scenarios = os.path.join(parent_directory,'B卷','驶入驶出停位')

# 定义匹配模式：以 "Scenario-shovel_loading_" 开头，后面跟着数字序号
pattern = r"Scenario-shovel_loading_(\d+)"

clear_and_copy_files_by_number(source_folder, source_folder_Scenarios, pattern)
